package com.tensquare.manager.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;

@Component
public class ManagerFilter extends ZuulFilter {


    @Autowired
    private JwtUtil jwtUtil;

    // pre在程序执行前执行
    // post相反
    @Override
    public String filterType() {
        return "pre";
    }

    // 执行顺序由大到小: 0~99...
    @Override
    public int filterOrder() {
        return 0;
    }

    // 是否执行 true执行 false相反
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 过滤器的具体逻辑
     *
     * @return 任何Object类型都行(也就是直接null)
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        System.out.println("ZuulFilter执行了!");
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();

        // 网关转发第一次分配请求是OPTIONS, 选择放行
        if (request.getMethod().equals("OPTIONS")) {
            return null;
        }
        // 如果返回索引位置大于0 就认为是登录请求
        if (request.getRequestURI().indexOf("login") > 0) {
            System.out.println(request.getRequestURI().toString());
            return null;
        }

        String header = request.getHeader("Authorization");
        if (header != null && !"".equals(header)) {
            if (header.startsWith("Bearer ")) {
                String token = header.substring(7);
                try {
                    Claims claims = jwtUtil.parseJWT(token);
                    String roles = (String) claims.get("roles");
                    if (roles.equals("admin")) {
                        context.addZuulRequestHeader("Authorization", header);
                        return null;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    context.setSendZuulResponse(false); // 终止运行
                }
            }
        }
        context.setSendZuulResponse(false); // 终止运行
        context.setResponseStatusCode(403);
        context.setResponseBody("无权访问");
        context.getResponse().setContentType("test/html;charset=UTF-8");
        return null;
    }

}
